#!/bin/bash
##############################################################################
# cron任务管理脚本
# 功能：安装、卸载、状态检查、立即执行
##############################################################################

SCRIPT_NAME="docker_restart_clean.sh"
CRON_TIME="0 2 * * *"
LOG_FILE="/var/log/cron_manager.log"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

find_script() {
    # 简化的查找逻辑
    if [ -f "./$SCRIPT_NAME" ]; then
        echo "./$SCRIPT_NAME"
    elif [ -f "/home/gitee/fastapi-baseline/$SCRIPT_NAME" ]; then
        echo "/home/gitee/fastapi-baseline/$SCRIPT_NAME"
    else
        return 1
    fi
}

install_cron() {
    local script_path=$(find_script)
    if [ $? -ne 0 ]; then
        log "错误：找不到脚本 $SCRIPT_NAME"
        return 1
    fi
    
    chmod +x "$script_path"
    (crontab -l 2>/dev/null | grep -v "$SCRIPT_NAME"; echo "$CRON_TIME /bin/bash $script_path") | crontab -
    log "cron任务安装完成"
}

uninstall_cron() {
    crontab -l 2>/dev/null | grep -v "$SCRIPT_NAME" | crontab -
    log "cron任务已卸载"
}

check_status() {
    echo "当前cron任务:"
    crontab -l 2>/dev/null | grep "$SCRIPT_NAME" || echo "未找到相关任务"
    
    echo -e "\n最近执行日志:"
    tail -10 /var/log/docker_restart_clean.log 2>/dev/null || echo "暂无日志"
}

run_now() {
    local script_path=$(find_script)
    if [ $? -eq 0 ]; then
        log "立即执行脚本..."
        /bin/bash "$script_path"
    else
        log "错误：找不到脚本"
    fi
}

case "$1" in
    install)
        install_cron
        ;;
    uninstall)
        uninstall_cron
        ;;
    status)
        check_status
        ;;
    run)
        run_now
        ;;
    *)
        echo "使用方法: $0 {install|uninstall|status|run}"
        echo "  install   - 安装cron任务"
        echo "  uninstall - 卸载cron任务"
        echo "  status    - 查看状态"
        echo "  run       - 立即执行"
        exit 1
        ;;
esac